package com.ls.security;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 * 
 * @ClassName: SimpleTest2
 * @Description: 简单的对称加密(二)
 * @author 我夕
 * @date 2012-5-15
 */
public class AesSecretWithDisk {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		
		//加密
		simpleSecret();
		//解密
		simpleDecret();

	}
	
	/**
	 * 加密方法
	 * @throws Exception
	 */
	public static void simpleSecret()throws Exception{
		//创建cipher对象实例
		Cipher cipher = Cipher.getInstance("AES");
		//创建key
		SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
		//将key保存到磁盘
		keySavaData(secretKey);
		//初始化
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		//加密数据
		byte[] result=cipher.doFinal("hello java!".getBytes());
		
		System.out.println("数据加密的结果："+new String(result));
		
		//讲加密的数据存到硬盘
		FileOutputStream fileOutputStream = new FileOutputStream("simple.data");
		fileOutputStream.write(result);
		fileOutputStream.close();
		
	}
	/**
	 * 解密方法
	 * @throws Exception
	 */
	public static void simpleDecret()throws Exception{
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, keyReadData());
		//从磁盘中读取数据的犯非法
		byte[] result = cipher.doFinal(readData(new FileInputStream("simple.data")));
		
		System.out.println("解密后的数据："+new String(result));
	}
	/**
	 * 将产生的密钥写到磁盘上
	 * @param key
	 * @throws Exception
	 */
	public static void keySavaData(SecretKey key)throws Exception{
		FileOutputStream fileOutputStream = new FileOutputStream("simple.key");
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
		objectOutputStream.writeObject(key);
		objectOutputStream.close();
		fileOutputStream.close();
	}
	/**
	 * 从磁盘中读取密钥
	 * @throws Exception
	 */
	public static Key keyReadData() throws Exception{
		FileInputStream fileInputStream = new FileInputStream("simple.key");
		ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
		Key key = (Key)objectInputStream.readObject();
		objectInputStream.close();
		fileInputStream.close();
		return key;
	}
	/**
	 * 从磁盘中读取数据
	 * @param inputStream
	 * @throws Exception
	 */
	public static byte[] readData(FileInputStream inputStream) throws Exception{
		ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream();
		int len=0;
		byte[] data=new byte[1024];
		while((len=inputStream.read(data))!=-1){
			arrayOutputStream.write(data, 0, len);
		}
		byte[] result=arrayOutputStream.toByteArray();
		arrayOutputStream.close();
		inputStream.close();
		
		return result;
	}

}


